import React, { createContext, useContext, useState, useEffect, ReactNode, useCallback } from 'react';
import { saveNovelMetadata, loadNovelMetadata, saveChapterContent, loadChapterContent, TreeItem as FileTreeItem, ItemType as FileItemType } from '../utils/file/fileSystem.ts';
import { useFileSync } from '../hooks/fileSystem/index.ts';
import { TreeItem, ItemType, Novel } from '../types/novel.ts';
import { FileHandle } from '../types/fileSystem.ts';
import { importer } from '../utils/fileSystem/index.ts';
import { ReplaceOperation } from '../types/ai.ts';

// 上下文接口
export interface NovelContextType {
  novels: TreeItem[];
  currentItem: TreeItem | null;
  setCurrentItem: (item: TreeItem | null) => void;
  addNovel: (name: string) => string;
  addVolume: (novelId: string, name: string) => string;
  addChapter: (volumeId: string, name: string) => string;
  updateItem: (id: string, updates: Partial<TreeItem>) => void;
  deleteItem: (id: string) => void;
  loadContent: (itemId: string) => Promise<string>;
  saveContent: (itemId: string, content: string) => Promise<void>;
  isLoading: boolean;
  moveItemUp: (id: string) => void;
  moveItemDown: (id: string) => void;
  setNovels: React.Dispatch<React.SetStateAction<TreeItem[]>>;
  importFromFileSystem: (novelStructure?: Novel) => Promise<boolean>;
  linkNovelToFolder: (novelId: string) => Promise<boolean>;
  syncWithFileSystem: (novelId: string) => Promise<boolean>;
  replaceSelectedText: (operation: ReplaceOperation) => Promise<boolean>;
}

// 创建上下文
const NovelContext = createContext<NovelContextType | undefined>(undefined);

// 将文件系统TreeItem转换为应用内TreeItem
const convertFileTreeItemToTreeItem = (fileItem: FileTreeItem): TreeItem => {
  return {
    id: fileItem.id,
    name: fileItem.name,
    type: fileItem.type === FileItemType.NOVEL ? ItemType.NOVEL :
      fileItem.type === FileItemType.VOLUME ? ItemType.VOLUME :
        ItemType.CHAPTER,
    content: fileItem.content,
    children: fileItem.children ? fileItem.children.map(convertFileTreeItemToTreeItem) : undefined,
  };
};

// 将应用内TreeItem转换为文件系统TreeItem
const convertTreeItemToFileTreeItem = (treeItem: TreeItem): FileTreeItem => {
  return {
    id: treeItem.id,
    name: treeItem.name,
    type: treeItem.type === ItemType.NOVEL ? FileItemType.NOVEL :
      treeItem.type === ItemType.VOLUME ? FileItemType.VOLUME :
        FileItemType.CHAPTER,
    content: treeItem.content,
    children: treeItem.children ? treeItem.children.map(convertTreeItemToFileTreeItem) : undefined,
  };
};

// 初始示例数据
const initialNovels: TreeItem[] = [
  {
    id: '1',
    name: '我的第一本小说',
    type: ItemType.NOVEL,
    children: [
      {
        id: '1-1',
        name: '第一卷',
        type: ItemType.VOLUME,
        children: [
          {
            id: '1-1-1',
            name: '第一章：开始',
            type: ItemType.CHAPTER,
            content: '这是第一章的内容。故事从这里开始...'
          },
          {
            id: '1-1-2',
            name: '第二章：发展',
            type: ItemType.CHAPTER,
            content: '这是第二章的内容。故事开始发展...'
          },
        ],
      },
      {
        id: '1-2',
        name: '第二卷',
        type: ItemType.VOLUME,
        children: [
          {
            id: '1-2-1',
            name: '第三章：高潮',
            type: ItemType.CHAPTER,
            content: '这是第三章的内容。故事达到高潮...'
          },
        ],
      },
    ],
  },
];

// Provider组件
interface NovelProviderProps {
  children: ReactNode;
}

export const NovelProvider: React.FC<NovelProviderProps> = ({ children }) => {
  const [novels, setNovels] = useState<TreeItem[]>(initialNovels);
  const [currentItem, setCurrentItem] = useState<TreeItem | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const { selectRootFolder, importNovelStructure, syncState } = useFileSync();

  // 初始化时从文件系统加载数据
  useEffect(() => {
    const loadNovels = async () => {
      try {
        setIsLoading(true);
        const loadedNovels = await loadNovelMetadata();

        if (loadedNovels && loadedNovels.length > 0) {
          // 转换为当前使用的TreeItem格式
          const convertedNovels = loadedNovels.map(convertFileTreeItemToTreeItem);
          setNovels(convertedNovels);
        }
      } catch (error) {
        console.error('加载小说数据失败:', error);
      } finally {
        setIsLoading(false);
      }
    };

    loadNovels();
  }, []);

  // 当novels变化时保存到文件系统
  useEffect(() => {
    if (!isLoading) {
      // 转换为文件系统使用的TreeItem格式
      const convertedNovels = novels.map(convertTreeItemToFileTreeItem);
      saveNovelMetadata(convertedNovels).catch(err => {
        console.error('保存小说元数据失败:', err);
      });
    }
  }, [novels, isLoading]);

  // 生成唯一ID
  const generateId = () => {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  };

  // 查找项目
  const findItem = (items: TreeItem[], id: string): TreeItem | null => {
    for (const item of items) {
      if (item.id === id) {
        return item;
      }
      if (item.children) {
        const found = findItem(item.children, id);
        if (found) {
          return found;
        }
      }
    }
    return null;
  };

  // 查找父项目
  const findParentItem = (items: TreeItem[], id: string, parent: TreeItem | null = null): TreeItem | null => {
    for (const item of items) {
      if (item.id === id) {
        return parent;
      }
      if (item.children) {
        const found = findParentItem(item.children, id, item);
        if (found) {
          return found;
        }
      }
    }
    return null;
  };

  // 添加小说
  const addNovel = (name: string) => {
    const newNovel: TreeItem = {
      id: generateId(),
      name,
      type: ItemType.NOVEL,
      children: [],
    };
    setNovels([...novels, newNovel]);
    return newNovel.id;
  };

  // 添加卷
  const addVolume = (novelId: string, name: string) => {
    const newVolume: TreeItem = {
      id: generateId(),
      name,
      type: ItemType.VOLUME,
      children: [],
    };

    setNovels(prev => {
      const updated = [...prev];
      const novel = findItem(updated, novelId);
      if (novel) {
        novel.children = novel.children ? [...novel.children, newVolume] : [newVolume];
      }
      return updated;
    });
    return newVolume.id;
  };

  // 添加章节
  const addChapter = (volumeId: string, name: string) => {
    const newChapter: TreeItem = {
      id: generateId(),
      name,
      type: ItemType.CHAPTER,
      content: '',
    };

    setNovels(prev => {
      const updated = [...prev];
      const volume = findItem(updated, volumeId);
      if (volume) {
        volume.children = volume.children ? [...volume.children, newChapter] : [newChapter];
      }
      return updated;
    });
    return newChapter.id;
  };

  // 更新项目
  const updateItem = (id: string, updates: Partial<TreeItem>) => {
    setNovels(prev => {
      const updated = [...prev];
      const item = findItem(updated, id);
      if (item) {
        Object.assign(item, updates);
      }
      return updated;
    });
  };

  // 删除项目
  const deleteItem = (id: string) => {
    setNovels(prev => {
      const updated = [...prev];
      const parent = findParentItem(updated, id);

      if (parent && parent.children) {
        parent.children = parent.children.filter(child => child.id !== id);
        return updated;
      } else if (!parent) {
        // 如果没有父项，说明是顶级小说
        return updated.filter(novel => novel.id !== id);
      }

      return updated;
    });
  };

  // 保存内容到内存和文件系统
  const saveContent = async (id: string, content: string): Promise<void> => {
    try {
      // 获取要保存的项目
      const item = findItem(novels, id);
      if (!item) {
        throw new Error('找不到要保存的项目');
      }

      // 更新内存中的内容
      setNovels(prev => {
        const updated = [...prev];
        const itemToUpdate = findItem(updated, id);
        if (itemToUpdate) {
          itemToUpdate.content = content;
        }
        return updated;
      });

      // 如果是章节，则保存到文件系统
      if (item.type === ItemType.CHAPTER) {
        const success = await saveChapterContent(id, content);
        if (!success) {
          throw new Error('保存章节到文件系统失败');
        }
        console.log('章节内容已保存到文件系统:', id);
      }
    } catch (e) {
      console.error('保存内容失败:', e);
      throw e; // 重新抛出异常，让调用者知道保存失败
    }
  };

  // 从文件系统加载内容
  const loadContent = async (id: string): Promise<string> => {
    try {
      // 获取要加载的项目
      const item = findItem(novels, id);
      if (!item) {
        throw new Error('找不到要加载的项目');
      }

      // 如果是章节并且它有fileHandle，优先从文件系统加载
      if (item.type === ItemType.CHAPTER) {
        // 先检查内存中是否有内容
        if (item.content) {
          console.log('从内存加载章节内容:', id);
          return item.content;
        }

        // 从文件系统加载
        console.log('从文件系统加载章节内容:', id);
        const content = await loadChapterContent(id);

        // 更新内存中的内容
        if (content) {
          setNovels(prev => {
            const updated = [...prev];
            const updatedItem = findItem(updated, id);
            if (updatedItem) {
              updatedItem.content = content;
            }
            return updated;
          });
          return content;
        } else {
          console.warn('文件系统中未找到章节内容:', id);
          return item.content || '';
        }
      }

      // 非章节类型或找不到文件，返回内存中的内容
      return item.content || '';
    } catch (e) {
      console.error('加载内容失败:', e);
      throw e;
    }
  };

  // 移动卷或章节上移
  const moveItemUp = (id: string) => {
    setNovels((prevNovels) => {
      const newNovels = JSON.parse(JSON.stringify(prevNovels));

      // 查找目标项及其父项
      let targetItem: TreeItem | null = null;
      let parentItem: TreeItem | null = null;
      let siblings: TreeItem[] = [];
      let index = -1;

      // 查找函数
      const findItem = (items: TreeItem[], parent: TreeItem | null = null): boolean => {
        for (let i = 0; i < items.length; i++) {
          if (items[i].id === id) {
            targetItem = items[i];
            parentItem = parent;
            siblings = items;
            index = i;
            return true;
          }

          // 安全地递归查找子项
          const children = items[i].children || [];
          if (children.length > 0 && findItem(children, items[i])) {
            return true;
          }
        }

        return false;
      };

      // 在树中查找项目
      findItem(newNovels);

      // 如果找到了目标项并且不是第一个
      if (targetItem && index > 0) {
        // 交换位置
        const temp = siblings[index];
        siblings[index] = siblings[index - 1];
        siblings[index - 1] = temp;
      }

      return newNovels;
    });
  };

  // 移动卷或章节下移
  const moveItemDown = (id: string) => {
    setNovels((prevNovels) => {
      const newNovels = JSON.parse(JSON.stringify(prevNovels));

      // 查找目标项及其父项
      let targetItem: TreeItem | null = null;
      let parentItem: TreeItem | null = null;
      let siblings: TreeItem[] = [];
      let index = -1;

      // 查找函数
      const findItem = (items: TreeItem[], parent: TreeItem | null = null): boolean => {
        for (let i = 0; i < items.length; i++) {
          if (items[i].id === id) {
            targetItem = items[i];
            parentItem = parent;
            siblings = items;
            index = i;
            return true;
          }

          // 安全地递归查找子项
          const children = items[i].children || [];
          if (children.length > 0 && findItem(children, items[i])) {
            return true;
          }
        }

        return false;
      };

      // 在树中查找项目
      findItem(newNovels);

      // 如果找到了目标项并且不是最后一个
      if (targetItem && index < siblings.length - 1) {
        // 交换位置
        const temp = siblings[index];
        siblings[index] = siblings[index + 1];
        siblings[index + 1] = temp;
      }

      return newNovels;
    });
  };

  // 从文件系统导入小说
  const importFromFileSystem = useCallback(async (novelStructure?: Novel) => {
    try {
      setIsLoading(true);

      let novelTree: TreeItem | null = null;

      // 如果提供了小说结构，直接使用
      if (novelStructure) {
        novelTree = novelStructure;
      } else {
        // 否则尝试从文件系统获取
        const importedStructure = await importNovelStructure();
        if (!importedStructure) {
          return false;
        }
        novelTree = importedStructure;
      }

      // 如果导入的是Novel类型，添加到novels列表
      if (novelTree) {
        // 检查是否已存在同名小说
        const existingNovelIndex = novels.findIndex(n => n.name === novelTree.name);

        if (existingNovelIndex >= 0) {
          // 更新现有小说
          setNovels(prev => {
            const updated = [...prev];
            // 将新小说的属性合并到现有小说中，保留ID
            updated[existingNovelIndex] = {
              ...novelTree,
              id: updated[existingNovelIndex].id // 保留原ID
            } as TreeItem;
            return updated;
          });
          console.log('更新小说成功:', novelTree.name);
        } else {
          // 添加新小说
          setNovels(prev => [...prev, novelTree as TreeItem]);
          console.log('导入新小说成功:', novelTree.name);
        }

        return true;
      }

      return false;
    } catch (error) {
      console.error('从文件系统导入小说失败:', error);
      return false;
    } finally {
      setIsLoading(false);
    }
  }, [importNovelStructure, novels]);

  // 将现有小说链接到文件夹
  const linkNovelToFolder = async (novelId: string): Promise<boolean> => {
    try {
      setIsLoading(true);

      // 查找小说
      const novel = findItem(novels, novelId);
      if (!novel) {
        console.error('小说不存在');
        setIsLoading(false);
        return false;
      }

      // 选择文件夹
      const result = await selectRootFolder();
      if (!result) {
        console.log('没有选择文件夹');
        setIsLoading(false);
        return false;
      }

      // 使用工具函数设置文件句柄
      const updatedItem = importer.setFileHandleForItem(novel, result.folder);

      // 更新小说
      updateItem(novelId, updatedItem);

      setIsLoading(false);
      return true;
    } catch (error) {
      console.error('链接小说到文件夹失败:', error);
      setIsLoading(false);
      return false;
    }
  };

  // 与文件系统同步
  const syncWithFileSystem = async (novelId: string): Promise<boolean> => {
    try {
      setIsLoading(true);

      // 查找小说
      const novel = findItem(novels, novelId) as Novel;
      if (!novel) {
        console.error('小说不存在');
        setIsLoading(false);
        return false;
      }

      // 获取文件句柄
      const fileHandle = importer.getFileHandleFromItem(novel);
      if (!fileHandle) {
        console.error('小说未链接到文件夹');
        setIsLoading(false);
        return false;
      }

      // 导入小说结构
      const novelStructure = await importNovelStructure();
      if (!novelStructure) {
        console.error('无法导入小说结构');
        setIsLoading(false);
        return false;
      }

      // 转换为小说并合并
      const importedNovel = importer.convertToNovelTree(novelStructure);
      const mergedNovel = importer.mergeNovelWithImported(novel, importedNovel);

      // 更新小说列表
      setNovels(prev => {
        const updated = [...prev];
        const index = updated.findIndex(n => n.id === novelId);
        if (index >= 0) {
          updated[index] = mergedNovel;
        }
        return updated;
      });

      setIsLoading(false);
      return true;
    } catch (error) {
      console.error('同步小说失败:', error);
      setIsLoading(false);
      return false;
    }
  };

  // 替换选中文本
  const replaceSelectedText = async (operation: ReplaceOperation): Promise<boolean> => {
    try {
      console.log('Starting replaceSelectedText with operation:', operation);
      if (!operation.selectionInfo || !operation.selectionInfo.sourceId) {
        console.error('替换文本操作缺少必要的信息');
        return false;
      }

      // 输出当前小说结构的ID列表，帮助诊断
      console.log('当前novels结构中的ID列表:', novels.map(novel => ({
        novelId: novel.id,
        novelName: novel.name,
        volumes: novel.children?.map(volume => ({
          volumeId: volume.id,
          volumeName: volume.name,
          chapters: volume.children?.map(chapter => ({
            chapterId: chapter.id,
            chapterName: chapter.name
          }))
        }))
      })));

      // 查找源文档
      const sourceItem = findItem(novels, operation.selectionInfo.sourceId);
      if (!sourceItem) {
        console.error(`找不到ID为${operation.selectionInfo.sourceId}的源文档`);
        
        // 进一步诊断：尝试通过名称查找
        const itemsByName = findItemsByName(novels, operation.selectionInfo.sourceId);
        if (itemsByName.length > 0) {
          console.log(`通过名称找到了${itemsByName.length}个可能的匹配项:`, 
            itemsByName.map(item => ({ id: item.id, name: item.name, type: item.type }))
          );
        } else {
          console.log('通过名称也找不到匹配项');
        }
        
        return false;
      }
      console.log('Source item found:', sourceItem);

      // 加载最新内容
      const content = await loadContent(sourceItem.id);
      if (!content) {
        console.error('无法加载源文档内容');
        return false;
      }

      // 执行替换
      const { startPosition, endPosition } = operation.selectionInfo;
      console.log('Selection positions:', { startPosition, endPosition, contentLength: content.length });
      
      // 验证选择范围是否有效
      if (
        startPosition < 0 || 
        endPosition > content.length || 
        startPosition >= endPosition
      ) {
        console.error('无效的选择范围', { startPosition, endPosition, contentLength: content.length });
        return false;
      }

      // 验证原始文本是否匹配
      const selectedText = content.substring(startPosition, endPosition);
      console.log('Text comparison:', { 
        expected: operation.originalText, 
        actual: selectedText
      });
      
      if (selectedText !== operation.originalText) {
        console.warn('原始文本不匹配，可能文档已被修改', { 
          expected: operation.originalText, 
          actual: selectedText 
        });
        
        // 尝试在当前文档中查找原始文本的位置
        const exactIndex = content.indexOf(operation.originalText);
        if (exactIndex >= 0) {
          console.log('Found exact match at index:', exactIndex);
          const newContent = 
            content.substring(0, exactIndex) + 
            operation.newText + 
            content.substring(exactIndex + operation.originalText.length);
          
          // 保存修改后的内容
          console.log('Saving content with exact match replacement');
          await saveContent(sourceItem.id, newContent);
          return true;
        }
      }

      // 执行替换
      console.log('Executing replacement at original positions');
      const newContent = 
        content.substring(0, startPosition) + 
        operation.newText + 
        content.substring(endPosition);

      // 保存修改后的内容
      console.log('Saving content with original position replacement');
      await saveContent(sourceItem.id, newContent);
      
      console.log('Text replacement successful');
      return true;
    } catch (error) {
      console.error('替换文本时出错:', error);
      return false;
    }
  };

  // 通过名称查找项目（辅助函数，用于诊断）
  const findItemsByName = (items: TreeItem[], name: string): TreeItem[] => {
    let results: TreeItem[] = [];
    
    for (const item of items) {
      if (item.name === name) {
        results.push(item);
      }
      
      if (item.children) {
        results = [...results, ...findItemsByName(item.children, name)];
      }
    }
    
    return results;
  };

  const value = {
    novels,
    setNovels,
    currentItem,
    setCurrentItem,
    addNovel,
    addVolume,
    addChapter,
    updateItem,
    deleteItem,
    loadContent,
    saveContent,
    isLoading,
    moveItemUp,
    moveItemDown,
    importFromFileSystem,
    linkNovelToFolder,
    syncWithFileSystem,
    replaceSelectedText,
  };

  return (
    <NovelContext.Provider value={value}>
      {children}
    </NovelContext.Provider>
  );
};

// 自定义Hook
export const useNovel = () => {
  const context = useContext(NovelContext);
  if (context === undefined) {
    throw new Error('useNovel must be used within a NovelProvider');
  }
  return context;
}; 